package cc.yiueil.config;

import cc.yiueil.filter.CaptchaFilter;
import cc.yiueil.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class SecurityConfig {
    @Autowired
    UserService userService;

    @Autowired
    CaptchaFilter captchaFilter;

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                // 将这个Filter添加到用户密码认证之前
                .addFilterBefore(captchaFilter, UsernamePasswordAuthenticationFilter.class)
                .authorizeHttpRequests(requests -> requests
                        .antMatchers("/customLogin", "/captcha", "/login.html").permitAll() // 允许访问
                        .anyRequest().authenticated() // 其他所有请求都拦截
                )
                // 自定义登录页
                .formLogin(form -> form
                        .loginProcessingUrl("/customLogin")
                        .loginPage("/login.html").defaultSuccessUrl("/"))
                // 登出重定向页面
                .logout(logout -> logout.logoutSuccessUrl("/login.html"));
        http.csrf().disable();
        http.userDetailsService(userService);
        return http.build();
    }
}
